from django.shortcuts import render 
from django.http import HttpResponse 
from hostinfo.models import Host 
from hostinfo.models import HostGroup 
import pickle 
import json,hashlib,time
# Create your views here. 
def index(req):
    if req.method == 'POST':
        pick_obj = json.loads(req.body)
        hostname = pick_obj['hostname']
        ip = pick_obj['ip']
        osversion = pick_obj['osversion']
        memory = pick_obj['memory']
        disk = pick_obj['disk']
        vendor_id = pick_obj['vendor_id']
        model_name = pick_obj['model_name']
        cpu_core = pick_obj['cpu_core']
        product = pick_obj['product']
        Manufacturer = pick_obj['Manufacturer']
        sn = pick_obj['sn']
        try:
            host = Host.objects.get(hostname=hostname)
        except:
            host = Host()
        host.hostname = hostname
        host.ip = ip
        host.osversion = osversion
        host.memory = memory
        host.disk = disk
        host.vendor_id = vendor_id
        host.model_name = model_name
        host.cpu_core = cpu_core
        host.product = product
        host.Manufacturer = Manufacturer
        host.sn = sn
        host.save()
        return HttpResponse('ok')
    else:
        return HttpResponse('')
def api_auth(func):
    def deco(request,*args,**kwargs):
        key='a$#ERsdf@!sdFEf%KDdalep;aidzke.,'
        token = request.META.get('HTTP_AUTH_KEY') or ""
        if token:
            client_md5 = token.split('|')[0]
            timestamp = token.split('|')[1]
            temp = '{key}|{time}'.format(key=key, time=timestamp)
            server_md5 = hashlib.sha256(temp.encode('utf-8')).hexdigest()
            now = time.time()
            if float(timestamp) + 5 < now:
                return HttpResponse('Validation timeout!')
            elif server_md5 != client_md5:
                return HttpResponse('Verification failure!')
            else:
                return func(request,*args,**kwargs)
        else:
            return HttpResponse('No token verification code!')        
    return deco 
@api_auth
def getjson(req):
    hg = HostGroup.objects.all()
    key = {}
    for g in hg:
        ret = {g.groupname:[]}
        for h in g.members.all():
            ret_h = h.ip
            ret[g.groupname].append(ret_h)
        key = dict(key,**ret)
    return HttpResponse(json.dumps(key))
def gettxt(req):
    str = ''
    hg = HostGroup.objects.all()
    for g in hg:
        str += '[' + g.groupname + ']' + '<br>'
        for h in g.members.all():
            str += h.ip + '<br>'
    return HttpResponse(str)

